﻿using System;
using Google.GData.Photos;
using Google.Picasa;

namespace TheOutfield.UmbExt.UniversalMediaPicker.Providers.Picasa
{
    public static class PicasaExtensions
    {
        public static MediaItem ToMediaItem(this Album col)
        {
            var mediaItem = new MediaItem
                       {
                           Id = col.Id,
                           Title = col.Title,
                           Icon = "mediaPicasa.gif",
                           HasChildren = col.NumPhotos > 0,
                           PreviewImageUrl = "",
                           Selectable = false
                       };

            return mediaItem;
        }

        public static MediaItem ToMediaItem(this Photo col)
        {
            var mediaItem = new MediaItem
                       {
                           Id = col.Id + "," + col.AlbumId,
                           Title = col.Title,
                           Icon = UmbracoIcons.MediaPhoto,
                           HasChildren = false,
                           PreviewImageUrl = GetThumb(col.PicasaEntry, 1),
                           Selectable = true,
                       };


            mediaItem.MetaData.Add("Size", col.Size.ToString());
            mediaItem.MetaData.Add("Height", col.PicasaEntry.Media.Content.Height);
            mediaItem.MetaData.Add("Width", col.PicasaEntry.Media.Content.Width);
            mediaItem.MetaData.Add("Created", ConvertFromUnixTimestamp(col.Timestamp).Date.ToString());
            mediaItem.MetaData.Add("Modified", col.Updated.Date.ToString());
            mediaItem.MetaData.Add("PhotoUrl", col.PhotoUri.ToString());
            mediaItem.MetaData.Add("ThumbSmall", GetThumb(col.PicasaEntry, 0));
            mediaItem.MetaData.Add("ThumbMedium", GetThumb(col.PicasaEntry, 1));
            mediaItem.MetaData.Add("ThumbLarge", GetThumb(col.PicasaEntry, 2));

            if (col.Latitude != -1)
                mediaItem.MetaData.Add("Latitude", col.Latitude.ToString());
            if (col.Longitude != -1)
                mediaItem.MetaData.Add("Longitude", col.Longitude.ToString());

            return mediaItem;
        }

        private static string GetThumb(PicasaEntry entry, int thumb)
        {
            var thumbPhoto = entry.Media.Thumbnails[thumb].Attributes["url"];
            return thumbPhoto == null ? "" : thumbPhoto.ToString();
        }

        static DateTime ConvertFromUnixTimestamp(double timestamp)
        {
            timestamp = timestamp / 1000;
            var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return origin.AddSeconds(timestamp);
        }
    }
}